//
//  CreateGameViewController.swift
//  FootballDataRecord
//
//  Created by Xx Jiang on 2020/1/6.
//  Copyright © 2020 Xx Jiang. All rights reserved.
//

import UIKit

import AssetsLibrary

import AVFoundation
import Photos
class CreateGameViewController: BaseViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    @IBOutlet weak var teamALogo: UIImageView!
    @IBOutlet weak var teamBLogo: UIImageView!
    @IBOutlet weak var teamAName: UITextField!
    @IBOutlet weak var teamBName: UITextField!
    @IBOutlet weak var teamAPlayerNumBT: UIButton!
    @IBOutlet weak var teamBPlayerNum: UIButton!
    
    var matchModel:MatchModel?
    var teamAModel:TeamModel?
    var teamBModel:TeamModel?
    
    
    @IBOutlet weak var backViewB: UIView!
    @IBOutlet weak var backViewA: UIView!
    var teamList:[TeamModel]?
    
    lazy var teamListViewA:TeamListView = {
        
        let listView = Bundle.main.loadNibNamed("TeamListView", owner: nil, options: nil)?.first as! TeamListView
        
        return listView
    }()
    lazy var teamListViewB:TeamListView = {
        
        let listView = Bundle.main.loadNibNamed("TeamListView", owner: nil, options: nil)?.first as! TeamListView
        
        return listView
    }()
    
    
    @IBOutlet weak var teamALogoButton: UIButton!
    @IBOutlet weak var teamBLogoButton: UIButton!
    weak var currentImageView:UIImageView!
    

    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if teamAModel != nil  && !DYStringIsEmpty(value: teamAModel?.teamID as AnyObject){
            teamAModel = TeamModel.getTeamModelWithTeamID(teamId: (teamAModel?.teamID!)!)
        }
        if teamBModel != nil  && !DYStringIsEmpty(value: teamBModel?.teamID as AnyObject){
                   teamBModel = TeamModel.getTeamModelWithTeamID(teamId: (teamBModel?.teamID!)!)
               }
    //如果进入创建比赛页 却没有创建队伍 ，直接点了返回 则删除此条比赛
           if DYStringIsEmpty(value: matchModel?.matchTeamA as AnyObject?) || DYStringIsEmpty(value: matchModel?.matchTeamB as AnyObject?)  {
               DHDataBaseOperate.deleteModelValueFromDB(model: matchModel!, mainKey: DHMatchId) { (rs) in
               }
           }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "创建比赛"
        self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
        setUI()
        teamAModel = TeamModel()
        teamBModel = TeamModel()
    }
    
    func setUI()  {
        teamAPlayerNumBT.tag = 0
        teamAPlayerNumBT.tag = 1
        let placeHolder = UILabel()
        placeHolder.textColor = #colorLiteral(red: 0.3725490196, green: 0.3490196078, blue: 0.3137254902, alpha: 1)
        placeHolder.text = "请输入队名"
        teamBName.addSubview(placeHolder)
        teamBName.setValue(placeHolder, forKey: "_placeholderLabel")
        let placeHolder2 = UILabel()
        placeHolder2.text = "请输入队名"
        placeHolder2.textColor = #colorLiteral(red: 0.3725490196, green: 0.3490196078, blue: 0.3137254902, alpha: 1)
        teamAName.addSubview(placeHolder2)
        teamAName.setValue(placeHolder2, forKey: "_placeholderLabel")
        
        backViewA.addSubview(self.teamListViewA)
        backViewB.addSubview(self.teamListViewB)
        
        teamListViewA.snp.makeConstraints { (make) in
            make.top.equalTo(teamAName.snp.top).offset(27)
            make.left.equalTo(teamAName.snp.left).offset(3)
            make.right.equalTo(teamAName.snp.right).offset(-3)
            make.height.equalTo(100)
        }
        teamListViewB.snp.makeConstraints { (make) in
            make.top.equalTo(teamBName.snp.top).offset(27)
            make.left.equalTo(teamBName.snp.left).offset(3)
            make.right.equalTo(teamBName.snp.right).offset(-3)
            make.height.equalTo(100)
        }
        teamListViewA.isHidden = true
        teamListViewB.isHidden = true
        
    }
    @IBAction func gotoAddPlayerViewController(_ sender: UIButton) {
        
        self.view.endEditing(true)
        
        let vc = AddPlayerViewController()
        if sender == teamAPlayerNumBT {
            if DYStringIsEmpty(value: teamAModel!.teamID as AnyObject?) {
                return
            }
            vc.teamModel = teamAModel
            
        }else{
            if DYStringIsEmpty(value: teamBModel!.teamID as AnyObject?) {
                return
            }
            vc.teamModel = teamBModel
        }
        vc.matchModel = matchModel
        vc.teamType = sender.tag
        
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func textDidChanged(_ sender: UITextField) {
        if sender == teamAName {
            
        }else{
            
        }
    }
    
    
    
    /// 通过输入的队名 进行数据库查找队伍
    /// - Parameter TFString: TF输入的字符串
    func searchTeamWithString(TFString:String) -> ([TeamModel]) {
        var teamList = [TeamModel]()
        var  sql:String?
        if TFString.count != 0 {
            sql = "select * from \(teamTableName) where \(DHTeamName) like %%\(TFString)%%"
        }else{
            sql = "select * from \(teamTableName)"
        }
        
        
        
        
        DHDataBaseOperate.searchDatasFromDB(sqlString: sql!) { (result) in
            if result is FMResultSet {
                let rs = result as! FMResultSet
                while rs.next() {
                    let teamModel = TeamModel()
                    teamModel.teamID = rs.string(forColumn: DHTeamID)
                    teamModel.teamHead = rs.string(forColumn: DHTeamHead)
                    teamModel.teamName = rs.string(forColumn: DHTeamName)
                    teamModel.teamWinOrLose = rs.string(forColumn: DHTeamWinOrLose)
                    teamModel.teamPlayerCount = Int(rs.int(forColumn: DHTeamPlayerCount)) as NSNumber
                    teamModel.shoufaCount = Int(rs.int(forColumn: DHTeamShouFaPlayerCount)) as NSNumber
                    teamModel.tibuCount = Int(rs.int(forColumn: DHTeamTiBuPlayerCount)) as NSNumber
                    teamModel.teamMatchDataId = rs.string(forColumn: DHTeamMatchDataId)
                    teamList.append(teamModel)
                }
                rs.close()
            }
        }
        return teamList
    }
    
    @IBAction func goToGameDetailViewController(_ sender: Any) {
        if matchModel != nil && !DYStringIsEmpty(value: matchModel?.matchTeamA as AnyObject?)  && !DYStringIsEmpty(value: matchModel?.matchTeamB as AnyObject?) {
            if(teamAModel?.shoufaCount != nil && teamBModel?.shoufaCount != nil) && (teamAModel?.shoufaCount?.intValue)! < 11 || (teamBModel?.shoufaCount?.intValue)! < 11 {
                Toast.makeText(view, message: "请完成两队的首发阵容", afterHideTime: 1.5)
                return
            }
            let dateModel = DateModel()
            dateModel.now()
            matchModel!.matchTime = "\(dateModel.year)-\(dateModel.month)-\(dateModel.day) \(dateModel.hour):\(dateModel.minute)"
            matchModel!.matchName = "\(dateModel.year)-\(dateModel.month)-\(dateModel.day)"+"日比赛"
            matchModel!.matchStatus = "0"
            
            let teamAMatchDataModel = MatchDataModel()
            let teamBMatchDataModel = MatchDataModel()
            
            teamAMatchDataModel.matchDataID = "\(matchModel?.matchId ?? "")_team_\(matchModel?.matchTeamA ?? "")"
            teamBMatchDataModel.matchDataID = "\(matchModel?.matchId ?? "")_team_\(matchModel?.matchTeamB ?? "")"
            
            DHDataBaseOperate.changeValuesWithModel(model: matchModel!, keys: ["mainKey":DHMatchId,"valueKey":[DHMatchTime,DHMatchName,DHMatchStatus,DHMatchTeamA,DHMatchTeamB]]) { (rs) in
                if rs.isEqual(1){
                    DispatchQueue.main.async {
                        let vc = AddGameDetailHomeViewController()
                        vc.matchModel = self.matchModel!
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                }
            }
        }else{
            Toast.makeText(self.view, message: "请先添加队伍与球员", afterHideTime: 1.5)
        }
    }
    
    @IBAction func changeTeamALogo(_ sender: Any) {
        self.view.endEditing(true)
        self.currentImageView = teamALogo
        alertController()
    }
    @IBAction func changeTeamBLogo(_ sender: Any) {
        
        self.view.endEditing(true)
        
        self.currentImageView = teamBLogo
        alertController()
    }
    //选择头像的弹窗
    func alertController(){
        
        let alertcontroller = UIAlertController.init(title: "选择队伍头像", message:nil, preferredStyle: .actionSheet)
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self
        let action1 = UIAlertAction.init(title: "相册", style: .default) { (alertAction) in
            imagePickerController.sourceType = .photoLibrary
            //检查是否有权限    相册---
            if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
                PHPhotoLibrary.requestAuthorization { (status) in
                    switch status{
                    case .notDetermined: //还没决定
                        break;
                    case .restricted: ////此应用程序没有被授权访问的照片数据
                        break;
                    case .denied: ////用户已经明确否认了这一照片数据的应用程序访问
                        let alert = UIAlertController.init(title: "提示", message: "请前往设置打开相册权限", preferredStyle: .alert)
                        let action = UIAlertAction.init(title: "确定", style: .default, handler: nil)
                        alert.addAction(action)
                        DispatchQueue.main.async {
                            self.present(alert, animated: true, completion: nil)
                        }
                        break
                    case .authorized: //已经有权限
                        DispatchQueue.main.async {
                            self.present(imagePickerController, animated: true, completion: nil)
                        }
                        break
                        
                    @unknown default:
                        break
                    }
                }
            }
        }
        
        
        
        //相机
        let action2 = UIAlertAction.init(title: "相机", style: .default) { (alertAction) in
            imagePickerController.sourceType = .camera
            
            AVCaptureDevice.requestAccess(for: AVMediaType.video) { response in
                if response {
                    DispatchQueue.main.async {
                        self.present(imagePickerController, animated: true, completion: nil)
                    }
                } else {
                    let alert = UIAlertController.init(title: "提示", message: "请前往设置打开相机权限", preferredStyle: .alert)
                    let action = UIAlertAction.init(title: "确定", style: .default, handler: nil)
                    alert.addAction(action)
                    DispatchQueue.main.async {
                        self.present(alert, animated: true, completion: nil)
                    }
                }
            }
        }
        alertcontroller.addAction(action1)
        alertcontroller.addAction(action2)
        let action3 = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        alertcontroller.addAction(action3)
        self.present(alertcontroller, animated: true, completion: nil)
    }
    
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        currentImageView.image = (info[UIImagePickerController.InfoKey.originalImage] as! UIImage)
        if picker.allowsEditing {
            currentImageView.image = (info[UIImagePickerController.InfoKey.editedImage] as! UIImage)
        }
        #if false
        if #available(iOS 11.0, *) {
            saveImage(imagePath: (info[UIImagePickerController.InfoKey.imageURL] as! NSURL).absoluteString!)
        } else {
            let alertC = UIAlertController.init(title: "提示", message: "系统版本过低，无法获取图片路径", preferredStyle: .alert)
            let action = UIAlertAction.init(title: "确定", style: .cancel) { (ac) in
                
            }
            alertC.addAction(action)
            self.present(alertC, animated: true, completion: nil)
            //            let imageurl = info[UIImagePickerController.InfoKey.referenceURL]
            //            let assetslibrary = ALAssetsLibrary.init()
            //            assetslibrary.asset(for: (imageurl as! URL), resultBlock: { (asset) in
            //                let representation = asset?.defaultRepresentation()
            //                print(representation?.url())
            //            }) { (error) in
            //
            //            }
            //            saveImage(imagePath: (info[UIImagePickerController.InfoKey.] as! String))
        }
        #endif
        
        saveImageToDocument(image: currentImageView.image!)
        
        
        dismiss(animated: true, completion: nil)
    }
     //保存图片到沙盒目录
    func saveImageToDocument(image:UIImage) {
        let imagePath = NSHomeDirectory().appending("/Documents/").appending("\(NSDate().timeIntervalSinceNow)")
        let imageData = image.jpegData(compressionQuality: 0.5)
        try! imageData?.write(to: URL.init(fileURLWithPath: imagePath))
        print("图片地址--->\n\(imagePath)")
        //保存图片地址到数据库 (判断是A队还是B队)
        if currentImageView == teamALogo {
            if teamAName.text!.count > 0{
                let teamodel = TeamModel.getTeamModelWithTeamID(teamId: teamAName.text!)
                if teamodel.teamID != nil {
                    teamodel.teamHead = imagePath
                    teamAModel = teamodel
                    updateTeamModel(model: teamodel, key: DHTeamHead)
                }
            }else{
                teamAModel?.teamHead = imagePath
            }
        }else{
            print("B队")
            if teamBName.text!.count > 0{
                let teamodel = TeamModel.getTeamModelWithTeamID(teamId: teamBName.text!)
                               if teamodel.teamID != nil {
                                   teamodel.teamHead = imagePath
                                teamBModel = teamodel
                                   updateTeamModel(model: teamodel, key: DHTeamHead)
                               }
//                TeamModel.getTeamModelWithTeamID(teamId: teamBName.text!) { (rs) in
//                    weakSelf!.teamBModel?.teamHead = imagePath
//                    if rs is TeamModel{
//                        DispatchQueue.main.async {
//                            weakSelf!.updateTeamModel(model: weakSelf!.teamBModel!, key: DHTeamHead)
//                        }
//                    }
//                }
            }else{
                teamBModel?.teamHead = imagePath
            }
        }
        
    }
    
    
    
    #if false
    func saveImage(imagePath:String) {

        weak var weakSelf = self
        //保存图片地址到数据库 (判断是A队还是B队)
        if currentImageView == teamALogo {
            if teamAName.text!.count > 0{
                TeamModel.getTeamModelWithTeamID(teamId: teamAName.text!) { (rs) in
                    weakSelf!.teamAModel?.teamHead = imagePath
                    if rs is TeamModel{
                        DispatchQueue.main.async {
                            weakSelf!.updateTeamModel(model: weakSelf!.teamAModel!, key: DHTeamHead)
                        }
                    }
                }
            }else{
                teamAModel?.teamHead = imagePath
            }
        }else{
            print("B队")
            if teamBName.text!.count > 0{
                TeamModel.getTeamModelWithTeamID(teamId: teamBName.text!) { (rs) in
                    weakSelf!.teamBModel?.teamHead = imagePath
                    if rs is TeamModel{
                        DispatchQueue.main.async {
                            weakSelf!.updateTeamModel(model: weakSelf!.teamBModel!, key: DHTeamHead)
                        }
                    }
                }
            }else{
                teamBModel?.teamHead = imagePath
            }
        }
        
    }
    #endif
    
}


extension CreateGameViewController:UITextFieldDelegate{
    #if false
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        teamList = searchTeamWithString(TFString: (textField.text?.count == 0) ? "":(textField.text!))
        if textField == teamAName {
            if teamList!.count > 0 {
                teamListViewA.isHidden = false
                teamListViewB.isHidden = true
                teamListViewA.dataSource = teamList!
            }else{
                teamListViewA.isHidden = true
                teamListViewB.isHidden = true
            }
        }else{
            
            if teamList!.count > 0 {
                teamListViewA.isHidden = true
                teamListViewB.isHidden = false
                teamListViewB.dataSource = teamList!
            }else{
                teamListViewA.isHidden = true
                teamListViewB.isHidden = true
            }
        }
    }
    
    
    #endif
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        
        textField.resignFirstResponder()
        return true
    }
    
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        if !(textField.text!.count > 0){
            return true
        }
        
        var searchTeamModel:TeamModel?
        TeamModel.getTeamModelWithTeamID(teamId: textField.text!) { (result) in
            if result is TeamModel{
                searchTeamModel = (result as! TeamModel)
            }
        }
        
        if (searchTeamModel != nil) && !(DYStringIsEmpty(value: searchTeamModel?.teamID as AnyObject?)) {
            if textField == teamAName {
                if DYStringIsEmpty(value: teamAModel!.teamHead as AnyObject?) {
                    if DYStringIsEmpty(value: searchTeamModel?.teamHead as AnyObject?) {
                        searchTeamModel?.teamHead = ""
                    }
                }else{
                    searchTeamModel!.teamHead = teamAModel?.teamHead
                    updateTeamModel(model: searchTeamModel!, key:DHTeamHead)
                }
                teamAModel = searchTeamModel
                teamALogo.image = getImage(path: DYStringIsEmpty(value: teamAModel!.teamHead as AnyObject?) ? "":teamAModel!.teamHead!)
                //                matchModel?.teamAModel = teamAModel
                matchModel?.matchTeamA = teamAModel?.teamID
                
            }else{
                if DYStringIsEmpty(value: teamBModel!.teamHead as AnyObject?){
                    if DYStringIsEmpty(value: searchTeamModel?.teamHead as AnyObject?) {
                        searchTeamModel?.teamHead = ""
                    }
                }else{
                    searchTeamModel!.teamHead = teamBModel?.teamHead
                    updateTeamModel(model: searchTeamModel!, key:DHTeamHead)
                }
                teamBModel = searchTeamModel
                teamBLogo.image = getImage(path: DYStringIsEmpty(value: teamBModel!.teamHead as AnyObject?) ? "":teamBModel!.teamHead!)
                
                //                matchModel?.teamBModel = teamBModel
                matchModel?.matchTeamB = teamBModel?.teamID
            }
            return true
        }
        
        if textField == teamAName {
            teamAModel?.teamName = textField.text
            teamAModel?.teamID = textField.text
            teamAModel?.teamHead = ""
            matchModel?.matchTeamA = teamAModel?.teamID
            inserModelToDB(model: teamAModel!)
        }else{
            teamBModel?.teamName = textField.text
            teamBModel?.teamID = textField.text
            teamAModel?.teamHead = ""
            matchModel?.matchTeamB = teamBModel?.teamID
            inserModelToDB(model: teamBModel!)
            
        }
        return true
    }
    
    
    func inserModelToDB(model:TeamModel){
        DHDataBaseOperate.insertModelToDB(model: model) { (success) in
            if (success as! Bool) {
                DispatchQueue.main.async {
                    let teamMatchDataModel = MatchDataModel()
                    teamMatchDataModel.matchDataID  = "\(self.matchModel?.matchId ?? "")_team_\(model.teamID ?? "")"
                    
                    DHDataBaseOperate.insertModelToDB(model: teamMatchDataModel) { (rs) in
                        if rs.isEqual(1){
                            print("插入成功")
                            model.teamMatchDataId = teamMatchDataModel.matchDataID
                            DispatchQueue.main.async {
                                self.updateTeamModel(model: model, key: DHTeamMatchDataId)
                            }
                        }
                    }
                }
            }else{
                print("error")
            }
        }
        
    }
    
    func updateTeamModel(model:TeamModel,key:Any){
        DHDataBaseOperate.changeValuesWithModel(model: model, keys: ["mainKey":DHTeamID,"valueKey":key]) { (rs) in
            if (rs as! Bool){
                print("修改成功")
            }else{
                print("修改失败")
            }
        }
    }
}




//}

